package com.l024.hi_device_util.contact;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wu_ming_zhi_bei
 * @date 2021/6/1 17:29
 * @Notes 抓取联系人
 */
public class ContactUtil {
    public static String permission = Manifest.permission.READ_CONTACTS;
    public static final int CONTACT_CODE = 1001;
    // 号码
    public final static String NUM = ContactsContract.CommonDataKinds.Phone.NUMBER;
    // 联系人姓名
    public final static String NAME = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME;
    //联系人提供者的uri
    private Uri phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

    public List<ContactModel> getContacts(Activity activity){
        List<ContactModel> contactModels = new ArrayList<>();
        ContentResolver cr = activity.getContentResolver();
        Cursor cursor = cr.query(phoneUri,new String[]{NUM,NAME},null,null,null);
        while (cursor.moveToNext()){
            ContactModel model = new ContactModel();
            model.setName(cursor.getString(cursor.getColumnIndex(NAME)));
            model.setPhone(cursor.getString(cursor.getColumnIndex(NUM)));
            contactModels.add(model);
        }
        return contactModels;
    }

    public boolean checkPermission(Activity activity){
        if(ContextCompat.checkSelfPermission(activity,permission)
                != PackageManager.PERMISSION_GRANTED){
            return false;
        }else{
            return true;
        }
    }
}
